const axios = require('axios');

class HttpSrv {
    static sHeaders = {'X-Requested-With': 'XMLHttpRequest'};
    static sEndPoint = 'hello';

    static setEndPoint(endPoint) {
        HttpSrv.sEndPoint = endPoint;
    }

    constructor() {
        this.headers = HttpSrv.sHeaders;
    }

    setUrl(url) {
        this.fullUrl = url;
        return this;
    }

    setPath(path) {
        this.fullUrl = HttpSrv.sEndPoint + path;
        return this;
    }

    setHeaders(headers) {
        this.headers = {
            ...this.headers,
            headers
        };
        return this;
    }

    setQuery(query) {
        this.query = query;
        return this;
    }

    setBody(body) {
        this.body = body;
        return this;
    }

    async getReq() {
        return await axios.get(this.fullUrl, {
            headers: this.headers,
            params: {
                ...this.query
            }
        }).then(result => result.data).catch(error => console.error(error));
    }

    async postReq() {
        return await axios.post(this.fullUrl, {
            headers: this.headers,
            data: {
                ...this.body
            }
        }).then(result => result.data).catch(error => console.error(error));
    }

    async putReq() {
        return await axios.put(this.fullUrl, {
            headers: this.headers,
            data: {
                ...this.body
            }
        }).then(result => result.data).catch(error => console.error(error));
    }

    async delReq() {
        return await axios.delete(this.fullUrl, {
            headers: this.headers,
            params: {
                ...this.query
            }
        }).then(result => result.data).catch(error => console.error(error));
    }
}

module.exports = HttpSrv;